--[[
    @desc 面向对象实现
    @author zch
    @data:2022-04-15 14:00:00
]]

local setmetatable = setmetatable
local getmetatable = getmetatable

-- 先调用父类的构造函数，再调用子类的构造函数
local function create(class, obj, ...)
    if class.super then
        create(class.super, obj, ...)
    end
    if class.__init then
        class.__init(obj, ...)
    end
end

-- 先调用子类的删除函数 再调用父类的删除函数
local function delete(self)
    local now_super = self._class_type
    while now_super ~= nil do
        if now_super.__delete then
            now_super.__delete(self)
        end
        now_super = now_super.super
    end
end

function BaseClass(super)
    local class_type =
    {
        __init = false,
        __delete = false,
        __index = false,
        New = false,
        super = false
    }

    class_type.super = super
    class_type.New = function(...)
        local obj =
        {
            _class_type = class_type,  --创建对象时要知道时哪个类创建的
            DeleteMe = delete,
        }
        local function newFunc(t, k)
            local ret = class_type[k]
            obj[k] = ret
            return ret
        end
        setmetatable(obj, {__index = newFunc})

        create(class_type, obj, ...)
        return obj
    end

    if super then
        --子类找不到的成员从父类中查找
        local function superFunc(t, k)
            local ret = super[k]
            class_type[k] = ret
            return ret
        end
        setmetatable(class_type, {__index = superFunc})
    end
    return class_type
end